#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function install_development() {
  sudo yum install -y python python2-setuptools
}

function download_flye() {
  echo "# FLYE正在下载"
  wget -t 40 -c "https://github.com/fenderglass/Flye/archive/refs/tags/2.9.tar.gz" -O "$1"/flye-2.9.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# FLYE已经下载成功\033[0m"
  else
    echo -e "\033[31m# FLYE下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_flye() {
  echo "# FlYE正在安装"
  tar xf "$1"/flye-2.9.tar.gz -C "$1" && rm -rf "$1"/flye-2.9.tar.gz
  cd "$1"/Flye-2.9
  cp $(get_current_dir)/python.default.patch ./
  patch -p2 <python.default.patch &>/dev/null
  CC=clang CXX=clang++ python setup.py install --prefix="$2"/flye-2.9  > $(get_current_dir)/make.log 2>&1
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# FLYE已经安装成功,编译详情请查看$(get_current_dir)/make.log\033[0m"
  else
    echo -e "\033[31m# FLYE安装失败,请查看$(get_current_dir)/make.log\033[0m"
    exit 1
  fi
}

function write_flye_module() {
  cat >"$1/flye-2.9/flye_2.9_modulefiles" <<EOF
#%Module1.0
conflict flye
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set FLYE \$pwd
setenv FLYE \$FLYE
prepend-path PATH \$FLYE/bin
prepend-path LD_LIBRARY_PATH \$FLYE/lib
prepend-path PYTHONPATH \$FLYE/lib/python2.7/site-packages
EOF
}

function main() {
  is_check_build_install_directory "$1" "$2" "flye-2.9.sh"
  is_check_build_equal "$1" "$2"
  install_development
  set +e
  download_flye "$1"
  install_flye "$1" "$2"
  set -e
  write_flye_module "$2"
  rm -rf "$1"/Flye-2.9
  echo "# ------------------------------------------------------------------------"
}

main "$@"
